/**
 * 
 */
package cn.nawang.ebeim.client;

import java.util.Iterator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.nawang.ebeim.client.bean.UploadProcessBarBean;
import cn.nawang.ebeim.client.util.DbUpDownloadUtil;
import cn.nawang.ebeim.client.util.DbUtil;
import cn.nawang.ebeim.client.util.UploadProcessBarList;

/**
 * @ClassName: UploadProcessBarThread
 * @Description: 上传进度条线程
 * @author zhangjf
 * @date 2015年10月14日09:57:36
 * @version v1.0
 */
public class UploadProcessBarThread implements Runnable{
  
  private static final Logger LOG = LoggerFactory.getLogger(UploadProcessBarThread.class);

  private int temp = 0;
  
  @Override
  public void run() {
    
    while(!AppMain.stopFlag.get()){
      for (String key : UploadProcessBarList.total.keySet()) {
        UploadProcessBarBean bean = DbUpDownloadUtil.getUploadProcessBar(key, DbUpDownloadUtil.PROCESS_BAR_STATUS_RUNNING);
        LOG.info("UploadProcessBarBean:"+bean);
        if(bean!=null){
//          if(bean.getCount() >= bean.getTotal()){
          if(bean.getCount() < bean.getTotal()){
//            DbUpDownloadUtil.updateUploadProcessBarStatus(bean.getDsId(), DbUpDownloadUtil.PROCESS_BAR_STATUS_SUCCESS);
//            System.out.println(".......bean.getCount() >= bean.getTotal().......");
//            Iterator it = UploadProcessBarList.total.keySet().iterator();
//            while(it.hasNext()) {
//              String dsId = (String) it.next();
//              if(dsId.equals(key)){
//                it.remove();
//              }
//            }
//            
//          }else{
            Long total = UploadProcessBarList.total.get(key);
            UploadProcessBarList.total.put(key, UploadProcessBarList.total.get(key)-total);
            DbUpDownloadUtil.updateUploadProcessBarCount(bean.getDsId(),bean.getCount()+total);
            LOG.info("summation:"+(UploadProcessBarList.total.get(key))+":"+total);
            
            if(temp%4==0){
              LOG.info("temp%4==0 into here...");
              int rest = DbUtil.getTaskStatusFileUnfinishedCount(DbUtil.TASK_TYPE_FILE, bean.getDsId());
              if(rest == 0){
                LOG.info("reset temp =0 into here***");
                temp = 0;
                DbUpDownloadUtil.updateUploadProcessBarCount(bean.getDsId(),bean.getTotal());
              }
            }
            temp ++;
            
          }
        }
      }
      
      try {
        Thread.sleep(2500);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    
  }

}
